<?php


namespace GordenSong\Support;


use GordenSong\Templates\TableValidatorCacheTemplate;
use Webmozart\Assert\Assert;

final class RuleCache
{
	private static $rules = [];

	public static function cacheFile($connection, $table): string
	{
		return (new TableValidatorCacheTemplate($connection, $table))->targetFile();
	}

	public static function cache(string $connection, string $table): array
	{
		if (isset(RuleCache::$rules[$connection]) && isset(RuleCache::$rules[$connection][$table])) {
			return RuleCache::$rules[$connection][$table];
		}

		$path = self::cacheFile($connection, $table);
		if (file_exists($path)) {
			$rules = require $path;
			if (is_array($rules)) {
				RuleCache::$rules[$connection][$table] = $rules;
			}
		}

		return data_get(RuleCache::$rules, "$connection.$table", []);
	}

	public static function getRules(string $connection, string $table): array
	{
		Assert::notNull($table);
		Assert::notNull($connection);

		return self::cache($connection, $table);
	}

	public static function getCache(): array
	{
		return self::$rules;
	}
}
